package com.antdsp.web.rest.sys;

import com.antdsp.common.annotation.OperationLog;
import com.antdsp.common.pagination.PaginationData;
import com.antdsp.dao.jpa.system.PermissionJpa;
import com.antdsp.dao.jpa.system.RoleJpa;
import com.antdsp.data.entity.system.SystemPermission;
import com.antdsp.data.entity.system.SystemRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system/permission")
public class SystemPermissionApi {

    @Autowired
    private PermissionJpa permissionJpa;

    @GetMapping("")
    @OperationLog(name="查询角色列表")
    public PaginationData<SystemPermission> list(int page , int count , String desc){

        int start = (page - 1) * count;
        Pageable pageable = PageRequest.of(start, count , Sort.by(Sort.Order.desc("created")));
        Specification<SystemPermission> specification = new Specification<SystemPermission>() {
            @Override
            public Predicate toPredicate(Root<SystemPermission> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

                List<Predicate> predicates = new ArrayList<>();
                if(!StringUtils.isEmpty(desc)) {
                    predicates.add(builder.like(root.get("desc"), "%"+desc+"%"));
                }
                return builder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Page<SystemPermission> permissionList = this.permissionJpa.findAll(specification , pageable);

        return new PaginationData<>(permissionList.getContent() , page , permissionList.getTotalElements());
    }
}
